package com.prp.gwt.client.widgets.user.profile;

import com.google.gwt.user.client.ui.FileUpload;
import com.google.gwt.user.client.ui.FormPanel;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.FormPanel.SubmitCompleteEvent;
import com.google.gwt.user.client.ui.FormPanel.SubmitCompleteHandler;
import com.prp.gwt.client.Host;
import com.prp.gwt.client.user.profile.ProfileListener;

public class PortraitUploadPanel extends HorizontalPanel{

	private static PortraitUploadPanel instance;
	private FileUpload upload;
	private HTML message = new HTML();
	private FormPanel form;
	private Image portrait = new Image();

	public static PortraitUploadPanel getInstance() {
		return instance;
	}

	public PortraitUploadPanel() {
		instance = this;
		portrait.setHeight("100px");
		add(portrait);
		add(getForm());
	}

	private FormPanel getForm() {
		form = new FormPanel();
		form.setAction(Host.getHOST()+"portraitUpload");
		form.setEncoding(FormPanel.ENCODING_MULTIPART);
		form.setMethod(FormPanel.METHOD_POST);
		VerticalPanel panel = new VerticalPanel();
		form.setWidget(panel);
		panel.add(new HTML("支持JPG、JPEG、GIF、BMP和PNG文件"));
		panel.add(new HTML("文件大小限制1M"));
		panel.setSpacing(10);
		upload = new FileUpload();
		upload.setName("upload");
		panel.add(upload);
		form.addSubmitCompleteHandler(new SubmitCompleteHandler(){
			@Override
			public void onSubmitComplete(SubmitCompleteEvent event) {
				ProfileView.getInstance().portraitLoadImage.setVisible(false);
				ProfileView.getInstance().portraitMessage.setText(event.getResults());
				ProfileListener.getInstance().refreshUser(-1);
			}
		});
		panel.add(message);
		return form;
	}

	public void setImage(String url) {
		portrait.setUrl(url);
	}

	public boolean upload(){
		message.setText("");
		String filename = upload.getFilename();
		String suffix = filename
				.substring(filename.lastIndexOf(".") + 1);
		if (suffix.equalsIgnoreCase("jpg")
				|| suffix.equalsIgnoreCase("jpeg")
				|| suffix.equalsIgnoreCase("gif")
				|| suffix.equalsIgnoreCase("bmp")
				|| suffix.equalsIgnoreCase("png")) {
			form.submit();
			return true;
		} else {
			message.setText("不支持此文件类型");
			return false;
		}
	}
	
}
